import cloud from '@lafjs/cloud'
import { updateUserInfo, deleteUser } from "@/thirdParty/moxueyuanUtils";
import { setMoXueYuanOrderUserInfo } from "@/admin/web/set_order_info";
const dbm = cloud.mongo.db

let data

export default async function (ctx: FunctionContext) {
  data = ctx.body.data //入参
  switch (ctx.body.type) {
    case "list":
      return list()
      break;
    case "update":
      return update()
      break;
    case "delete":
      return delFunc()
      break;
    case "setPublished"://设为公布
      return setPublished()
    case "setPublishedNo"://撤销公布
      return setPublishedNo()
      break;
    case "historicalRecords"://历史删除记录
      return historicalRecords()
      break;
    case "historyDict"://历史记录里的字典
      return historyDict()
    case "historicalRecordsQuery"://历史删除记录不分页
      return historicalRecordsQuery()
      break;
    case "updateMoxueyuanlatestTime"://魔学院匹配信息中间页最新更新时间戳
      return updateMoxueyuanlatestTime()
      break;
    default:
      break;
  }
}

//撤销公布
async function setPublishedNo() {
  for (let index = 0; index < data.out_trade_no.length; index++) {
    const element = data.out_trade_no[index];
    await dbm.collection('web-order').updateMany(
      { out_trade_no: element },
      {
        $unset: { isMoXueYuanPublished: 1 }
      }
    )
  }
  await dbm.collection('moxueyuan-order-list').updateMany({
    _id: data.orderId
  }, {
    $unset: { isMoXueYuanPublished: 1 }
  })
  return cloud.utils.requestReturn({ data: "" })
}

//设为公布
async function setPublished() {
  let isMoXueYuanPublished = {
    currentTrainTotal: data.currentTrainTotal,
    nowTime: data.nowTime
  }
  for (let index = 0; index < data.out_trade_no.length; index++) {
    const element = data.out_trade_no[index];
    await dbm.collection('web-order').updateMany(
      { out_trade_no: element },
      {
        $set: { isMoXueYuanPublished }
      }
    )
  }
  await dbm.collection('moxueyuan-order-list').updateMany(
    { _id: data.orderId },
    {
      $set: { isMoXueYuanPublished }
    }
  )
  return cloud.utils.requestReturn({ data: "" })
}

//历史删除记录的字典
async function historyDict() {
  let { key } = data
  let arr = []
  let aa = await dbm.collection("moxueyuan-del-account-list").find({}).toArray()
  aa.forEach(element => {
    arr.push(element[key])
  });
  return cloud.utils.requestReturn({ data: cloud.utils.unique(arr) })
}

//历史删除不分页
async function historicalRecordsQuery() {
  let whereJson = await setQueryParams()
  let res = await dbm.collection("moxueyuan-del-account-list").find(whereJson).sort({ registrationTime: -1 }).toArray()
  return cloud.utils.requestReturn({ data: res })
}

async function setQueryParams() {
  let whereJson = cloud.utils.fuzzyQuery(data)
  delete whereJson.pageIndex
  delete whereJson.pageSize
  delete whereJson.learningTime
  delete whereJson.totalLearningTime
  delete whereJson.examScores
  delete whereJson.passExam

  let mobiles = <any>[]  //符合要求的手机号
  let isSearchMobile = false //是否查询过手机号

  //如果有时间筛选
  if (data.year) {
    const startOfYear = new Date(data.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(data.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳
    whereJson["registrationTime"] = { $gt: startOfYear, $lt: endOfYear }
    delete whereJson.year
  }
  const resp = await dbm.collection("moxueyuan-del-account-list").find({}).toArray()

  if (data.learningTime || data.totalLearningTime) {
    let list = <any>[]
    for (let index = 0; index < resp.length; index++) {
      const element = resp[index];
      //有效学时
      if (element.learningTime && element.learningTime != "-") {
        let timeObj = extractTime(element.learningTime);
        if (timeObj && timeObj.hours) {
          if (Number(timeObj.hours) >= Number(data.learningTime)) {
            list.push(element.mobile)
          }
        }
      }
      //累计学时
      if (element.totalLearningTime && element.totalLearningTime != "-") {
        let timeObj = extractTime(element.totalLearningTime);
        if (timeObj && timeObj.hours) {
          if (Number(timeObj.hours) >= Number(data.totalLearningTime)) {
            list.push(element.mobile)
          }
        }
      }
    }
    isSearchMobile = true
    if (list.length) mobiles = cloud.utils.getCommonElements([...mobiles], list)
  }

  //考试分数
  if (data.examScores) {
    let list = <any>[]
    resp.forEach(element => {
      if (element.exam_scores && element.exam_scores.length) {
        let amount = 0
        let arr = <any>[]
        element.exam_scores.forEach(item => {
          if (item.stateValue == 2) {
            amount += Number(item.score);
            arr.push(item)
          }
        });
        if (amount && ((amount / arr.length) >= Number(data.examScores))) {
          list.push(element.mobile)
        }
      }
    });
    isSearchMobile = true
    if (list.length) mobiles = cloud.utils.getCommonElements([...mobiles], list)
  }

  //合格
  if (data.passExam) {
    let list = <any>[]
    resp.forEach(element => {
      if (Number(element.passExam) >= Number(data.passExam)) list.push(element.mobile)
    });
    isSearchMobile = true
    if (list.length) mobiles = cloud.utils.getCommonElements([...mobiles], list)
  }

  if (isSearchMobile && mobiles.length) whereJson["mobile"] = { $in: mobiles }
  return whereJson
}

//历史删除记录
async function historicalRecords() {
  let whereJson = await setQueryParams()
  console.log("历史魔学院删除记录入参", whereJson)

  let res = await cloud.nw.db.select({
    dbName: "moxueyuan-del-account-list",
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson,
    sortArr: [{ "name": "registrationTime", "type": "desc" }],
  });
  return cloud.utils.requestReturn({ data: res })
}

async function delFunc() {
  try {
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      let { userid } = await cloud.nw.db.findByWhereJson({
        dbName: "moxueyuan-user-detail",
        whereJson: { mobile: element.mobile },
      });
      if (userid) {
        element.userid = userid
        await deleteUser(element)
      }
    }
    return cloud.utils.requestReturn({ data: "删除成功" })
  } catch (error) {
    console.log('删除魔学院有报错吗', error)
  }
}



async function update() {
  let obj = {}
  if (data.userid) obj['userid'] = data.userid
  if (data.mobile) obj['mobile'] = data.mobile
  let res = await cloud.nw.db.findByWhereJson({
    dbName: "moxueyuan-user-detail",
    whereJson: obj,
  });
  if (res && res._id) {
    if (!data.userid) data.userid = res.userid
    await updateUserInfo(data)
    await setMoXueYuanOrderUserInfo(data.userid)
    return cloud.utils.requestReturn({ data: "更新成功" })
  } else {
    return cloud.utils.requestReturn({ code: 500, msg: `手机号${data.mobile},魔学院用户不存在` })
  }
}

//莫学院最新地址
async function updateMoxueyuanlatestTime() {
  let aa = await dbm.collection("moxueyuan-order-list").find({}).sort({ dataUpdateTime: -1 }).limit(1).toArray()
  return cloud.utils.requestReturn({ data: aa[0] })
}

async function list() {
  let whereJson = {}
  let withinScopeOrders = []
  if (data.disabled) whereJson["user_detail_info.disabled"] = data.disabled

  if ([0, 1].includes(data.isRepeat)) whereJson["isRepeat"] = data.isRepeat

  //如果有时间筛选
  if (data.year) {
    //传入年份的start和end内
    const startOfYear = new Date(data.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(data.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳

    //判断是否有挪至次年的标记，有的话是否等于传入的年份
    let aa = await dbm.collection("web-order").find({
      statisticsYear: {
        $exists: true,   // 判断属性存在[1,2](@ref)
        $eq: data.year        // 验证值等于2025[5](@ref)
      }
    }).project({ _id: 1 }).toArray()

    //没有标记，正常筛选
    let timeobj = {
      _add_time: { $gte: startOfYear, $lt: endOfYear },
      statisticsYear: { $exists: false }
    }
    let bb = await dbm.collection("web-order").find(timeobj).project({ _id: 1 }).toArray()

    let cc = [...aa, ...bb]
    cc.forEach(element => {
      withinScopeOrders.push(element._id)
    });

    whereJson["_id"] = { $in: withinScopeOrders } //特定的订单id
  }

  //如果对公布进行筛选
  if (data.isMoXueYuanPublished) {
    whereJson["isMoXueYuanPublished"] = { "$exists": data.isMoXueYuanPublished == 1 ? true : false }
  }

  //课程标签筛选
  if (data.tags && data.tags.length) {
    whereJson["tags"] = { $in: data.tags }
  }

  //姓名筛选
  if (data.name) {
    whereJson["approvalContent.model.name"] = { $regex: data.name.toString(), $options: "i" }
  }

  //手机号筛选
  if (data.mobile) whereJson["approvalContent.model.mobile"] = { $regex: data.mobile.toString(), $options: "i" }

  //培训完成状态
  if ((data.trainCompleted || data.trainCompleted == 0) && [0, 1].includes(data.trainCompleted)) {
    whereJson["trainCompleted"] = data.trainCompleted
  }

  //身份证筛选
  if (data.identityCard) {
    whereJson["approvalContent.model.identityCard"] = { $regex: data.identityCard.toString(), $options: "i" }
  }

  //用户id
  if (data.userId) whereJson["userId"] = { $regex: data.userId.toString(), $options: "i" }

  //订单号
  if (data.out_trade_no) whereJson["out_trade_no_string"] = { $regex: data.out_trade_no.toString(), $options: "i" }

  //订单自带的课程筛选
  if (data.curriculum_id && data.curriculum_id.length) whereJson["curriculum_id"] = { $in: data.curriculum_id }

  console.log("魔学院", whereJson)

  let res = await cloud.nw.db.selects({
    dbName: "moxueyuan-order-list",
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    // 主表 where 条件
    whereJson,
    // 主表字段显示规则
    fieldJson: {},
    sortArr: [
      { "name": "published", "type": "desc" },
      { "name": "isRepeat", "type": "desc" },
      { "name": "_add_time", "type": "desc" },
    ],
    // 主表排序规则
    // 副表列表
    foreignDB: [
      // {
      //   dbName: "web-course",//副表 order
      //   localKey: "curriculum_id",
      //   foreignKey: "_id",
      //   as: "course_info",
      //   limit: 1,
      //   // 副表 where 条件
      //   whereJson: {},
      //   // 副表字段显示规则
      //   fieldJson: { name: true, },
      // },
      // {
      //   dbName: "moxueyuan-user-count",//副表 vip
      //   localKey: "userId",
      //   foreignKey: "userid",
      //   as: "user_count_info",
      //   limit: 1,
      //   fieldJson: { passExam: true, learningTime: true, },
      // },
      // {
      //   dbName: "moxueyuan-user-detail",//副表 vip
      //   localKey: "mobile",
      //   foreignKey: "mobile",
      //   as: "user_detail_info",
      //   limit: 1,
      //   fieldJson: { role: true, userid: true, mobile: true, disabled: true, addTime: true, name: true, tagList: true },
      // },
      // {
      //   dbName: "moxueyuan-examUsers-statistics",
      //   localKey: "mobile",
      //   foreignKey: "mobile",
      //   as: "examUsers_info",
      //   limit: 10,
      //   fieldJson: { stateValue: true, score: true, },
      // },
      // {
      //   dbName: "moxueyuan-user-statistics",//副表 vip
      //   localKey: "mobile",
      //   foreignKey: "mobile",
      //   as: "user_statistics_info",
      //   limit: 1,
      //   fieldJson: { lastActiveTime: true, department: true, totalLearningTime: true, completedTrain: true },
      // }
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}

function extractTime(str) {
  var matches = str.match(/(\d+)\s*小时\s*(\d+)\s*分\s*(\d+)\s*秒/);
  if (matches) {
    return {
      hours: parseInt(matches[1], 10),
      minutes: parseInt(matches[2], 10),
      seconds: parseInt(matches[3], 10),
    };
  }
  return null;
}

function mergeUserLists(arrayA, arrayB) {
  // 创建以userid为键的Map，提高查找效率
  const mapB = new Map();
  arrayB.forEach(item => {
    mapB.set(item.userid, item);
  });
  // 遍历数组A，匹配相同userid
  const result = [];
  arrayA.forEach(itemA => {
    const userid = itemA.userid;
    const itemB = mapB.get(userid);
    // 如果数组B中存在相同userid
    if (itemB) {
      result.push({
        userid: userid,
        mobile: itemB.mobile,
        tagList: itemB.tagList,
        completedTrain: itemA.completedTrain
      });
    }
  });
  return result;
}